package cn.thinkcloud.corpwx.worksign.service;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.thinkcloud.corpwx.worksign.component.ScheduledRunnable;
import cn.thinkcloud.corpwx.worksign.utils.http.HttpAPIService;

@Service("updateAccessToken")
public class UpdateAccessTokenScheduleTask implements ScheduledRunnable {
	private final static Logger logger = LoggerFactory.getLogger(UpdateAccessTokenScheduleTask.class);

	public static final String _GETTOKEN_API_ = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

	@Resource
    private HttpAPIService httpAPIService;
	
    @Value("${wxbiz.corpid}")
    private String corpid;
    @Value("${wxbiz.corpsecret}")
    private String corpsecret;
    
    @Value("${javax.net.ssl.trustStore}")
    private String javaxNetSslTrustStore;
    
    @Value("${javax.net.ssl.trustStorePassword}")
    private String javaxNetSslTrustStorePassword;
    private String accessToken;
    private long lastUpdateTick = 0;
    private long validDuration;
	
	@Override
	public void execute() {
		String url = _GETTOKEN_API_ + "?corpid=" + corpid +
				"&corpsecret=" + corpsecret;
		
		long curTick = System.currentTimeMillis();
		if (lastUpdateTick != 0 && curTick-lastUpdateTick < validDuration )
			return;
		
		try {
			logger.info("update access token: {}", url);
			
//			System.setProperty("javax.net.ssl.trustStore", javaxNetSslTrustStore);
//			System.setProperty("javax.net.ssl.trustStorePassword", javaxNetSslTrustStorePassword);
//			System.setProperty("javax.net.ssl.trustStoreType", "pkcs12");
//			logger.info("javax.net.ssl.trustStore： {}", System.getProperty("javax.net.ssl.trustStore"));
//			logger.info("javax.net.ssl.trustStorePassword： {}", System.getProperty("javax.net.ssl.trustStorePassword"));
//			logger.info("javax.net.ssl.trustStoreType： {}", System.getProperty("javax.net.ssl.trustStoreType"));
			
			String str = httpAPIService.doGet(url);
			
			JSONObject jsonObject = JSONObject.parseObject(str);
			
			int errcode = (int) jsonObject.get("errcode");
			if (errcode != 0) {
				System.out.println("Error: " + jsonObject.get("errmsg"));
				return;
			}
			
			accessToken = jsonObject.getString("access_token");
			validDuration = 1000L * (long)jsonObject.getLongValue("expires_in");
			lastUpdateTick = curTick;

			System.out.println(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @return the accessToken
	 */
	public String getAccessToken() {
		return accessToken;
	}


}
